<template>
  <span
    v-if="currOption.color"
    class="cc-dict-label"
    :style="'background: ' + currOption.color"
  >{{currOption.value}}</span>
  <span v-else>{{currOption.value}}</span>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { getDictionary } from '@/utils/system';
import emitter from "@/utils/bus";

const props = defineProps({
  dictCode: String,
  dictValue: String,
})

const options = ref([]);
const currOption = ref({});

const init = async() => {
  currOption.value = {};
  await loadDicAndShow(props.dictCode);

  if (props.dictValue) {
    currOption.value = options.value.find(item => item.key === props.dictValue) || {};
  }
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    options.value = [];
  } else {
    options.value = await getDictionary(dictCode);
  }
};

watch(() => props, () => {
  init();
}, {immediate: true, deep: 1});

onMounted(() => {
  emitter.off("dictionary.change", init);
  emitter.on("dictionary.change", init);
});

onUnmounted(() => {
  emitter.off("dictionary.change", init);
});
</script>